package cn.px.common.exception;

import cn.px.common.enums.ResultCode;
import cn.px.common.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @Description 全局的的异常处理器
 * @author 品讯科技
 * @date 2024-08
 * @Version Copyright (c) 2019,北京乾元坤和科技有限公司 All rights reserved.
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 全局异常.
     *
     * @param e the e
     * @return R
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R exception(Exception e) {
        log.error("全局异常信息 ex={}", e.getMessage(), e);
        return new R<>(e);
    }

    /**
     * validation Exception
     *
     * @param exception
     * @return R
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R bodyValidExceptionHandler(MethodArgumentNotValidException exception) {
        List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
        R result = new R();
        result.setMessage(fieldErrors.get(0).getDefaultMessage());
        result.setCode(ResultCode.PARAM_INVALID.getCode());
        return result;
    }

    /**
     * param validation Exception
     *
     * @param exception
     * @return R
     */
    @ExceptionHandler({BindException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R bodyValidExceptionHandler(BindException exception) {
        R result = new R();
        result.setMessage(exception.getBindingResult().getFieldError().getDefaultMessage());
        result.setCode(ResultCode.PARAM_INVALID.getCode());
        return result;
    }

    /**
     * param validation Exception
     *
     * @param exception
     * @return R
     */
    @ExceptionHandler({BusinessException.class})
    @ResponseStatus(HttpStatus.OK)
    public R bodyValidExceptionHandler(BusinessException exception) {
        R result = new R();
        result.setMessage(exception.getMessage());
        result.setCode(exception.getCode());
        return result;
    }

}
